import { Router } from 'express';
import axios from 'axios';
import { db } from '../services/db';
import { IWxToken } from '../models/wx-token';
import { User } from '../models/auth';
import jwt from 'jsonwebtoken';

export const authLoginRouter: Router = Router();


authLoginRouter.get("", async (req, res, next) => {
    const redirect_uri = <string>req.query.redirect_uri;
    // 根据微信开发文档 https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#0
    let url = process.env.WX_APP_ID == null
        ? `${(req.protocol=="https" ? "https" : "http")}://${req.host}/api/auth/login/FakeWeixinLogin?redirect_uri=${encodeURIComponent(redirect_uri)}&response_type=code&scope=snsapi_base#wechat_redirect`
        : `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${process.env.WX_APP_ID}&redirect_uri=${encodeURIComponent(redirect_uri)}&response_type=code&scope=snsapi_base#wechat_redirect`;
    return res.redirect(url);
});

authLoginRouter.get("/FakeWeixinLogin", async (req, res, next) => {
    const redirect_uri = <string>req.query.redirect_uri;
    return res.redirect(`${redirect_uri}?code=1116`);
});

authLoginRouter.get("/Token", async (req, res, next): Promise<any> => {
    const code = <string>req.query.code;
    let wxOpenId: string | undefined;
    if (process.env.WX_APP_ID != null) {
        // 根据微信开发文档 https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#1
        const response = await axios.get(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${process.env.WX_APP_ID}&secret=${process.env.WX_APP_SECRET}&code=${code}&grant_type=authorization_code`);
        const wxToken: IWxToken = response.data;
        if (wxToken == null)
            return res.status(500).json({ title: "微信ID返回空值" });
        else if (wxToken.errcode != null)
            return res.status(500).json({ title: "微信ID返回错误" });
        else {
            wxOpenId = wxToken.openid;
            wxToken.createdAt = new Date();
            await db.wxTokens.insertOne(wxToken);
        }
    }
    else {
        // 开发环境执行
        wxOpenId = code;
    }
    var user = await db.users.findOne({ wxOpenId });
    if (user == null) {
        user = new User();
        user.wxOpenId = wxOpenId;
        const result = await db.users.insertOne(user);
        user._id = result.insertedId;
    }

    var token = jwt.sign(user, <string>process.env.JWT_KEY, { expiresIn: '7200s' });;

    return res.status(200).json(
        {
            token,
            user
        });
});
